package org.vaadin.addon.scrollpanel.client.ui;

import java.util.Set;

import org.vaadin.addon.scrollpanel.client.ui.widget.ScrollPanelGWT;

import com.google.gwt.user.client.ui.Widget;
import com.vaadin.terminal.gwt.client.ApplicationConnection;
import com.vaadin.terminal.gwt.client.Container;
import com.vaadin.terminal.gwt.client.Paintable;
import com.vaadin.terminal.gwt.client.RenderSpace;
import com.vaadin.terminal.gwt.client.UIDL;

public class VScrollPanel extends ScrollPanelGWT implements Container {

	protected String paintableId;

	protected ApplicationConnection client;
	
	protected Paintable content;
	
	public VScrollPanel() {
	    super();
	}

	public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
		if (client.updateComponent(this, uidl, true)) {
			return;
		}
		
		this.client = client;
		paintableId = uidl.getId();
		
        final UIDL contentUidl = uidl.getChildUIDL(0);
        updateContent(contentUidl);
        
	}

	@Override
	public void setWidth(String width) {
	    super.setWidth(width);
	    updateScrollbars();
	}
	
	@Override
	public void setHeight(String height) {
	    super.setHeight(height);
	    updateScrollbars();
	}
	
    private void updateContent(final UIDL contentUidl) {
        final Paintable paintable = client.getPaintable(contentUidl);
        if (paintable != content) {
            if (content != null) {   
                remove((Widget)content);
            }
            content = paintable;
            insert((Widget)paintable, 0);
        }
        paintable.updateFromUIDL(contentUidl, client);
    }

    @Override
    public void replaceChildComponent(Widget oldComponent, Widget newComponent) {
    }

    @Override
    public boolean hasChildComponent(Widget component) {
        return component == (Widget)content;
    }

    @Override
    public void updateCaption(Paintable component, UIDL uidl) {
    }

    @Override
    public boolean requestLayout(Set<Paintable> children) {
        if (!children.isEmpty()) {
            final Paintable paintable = children.iterator().next();
            if (paintable == content) {
                updateScrollbars();
            }
        }
        return true;
    }

    @Override
    public RenderSpace getAllocatedSpace(Widget child) {
        if (child == content) {
            return new RenderSpace(getOffsetWidth(), getOffsetHeight());
        }
        return null;
    }
}
